/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.cjb.malacma.rssfeed.util;

import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.util.Iterator;
import java.util.List;
import javax.persistence.Query;
import javax.servlet.http.*;
import net.cjb.malacma.rssfeed.crawler.FeedCrawler;
import net.cjb.malacma.rssfeed.entity.FeedUrl;
import net.cjb.malacma.rssfeed.googleapi.BloggerClient;
import websphinx.Link;

/**
 *
 * @author malacma
 */
public class FeedFacade {

    /**
     *
     * @ Salva o Feed na base para futuras consultas;
     * em uma nova thread
     */
    public static final void persistFeedUrl(final String url, final String tit) {
        Runnable r1 = new Runnable() {

            public void run() {
                FeedUrl fu = new FeedUrl();
                fu.setUrl(url);
                fu.setTitulo(tit);

                PersistenceUtil.persist(fu);
                //Adiciona no catálogo
                FeedCatalog.addFeed(fu);
                fu = null;
            }
        };
        if (!FeedCatalog.getInstance().containsKey(tit)) {
            Thread t1 = new Thread(r1);
            t1.start();
        }
    }

    public static final SyndFeed getLastSyndFeed() {
        FeedUrl fu = PersistenceUtil.getLastFeedUrl();
        SyndFeed sf = null;
        try {
            sf = FeedFactory.getInstance(fu.getUrl());
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return sf;

        }

    }

    public static void processFeedInfo(PrintWriter out, StringBuilder sb1, StringBuilder sb2, StringBuilder sb3, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {

            //Instância o FEED
            SyndFeed sf = (request.getParameter("rss") != null ? FeedFactory.getInstance(request.getParameter("rss").toString()) : FeedFacade.getLastSyndFeed());

            //Grava a URL
            if (request.getParameter("rss") != null) {
                FeedFacade.persistFeedUrl(request.getParameter("rss").toString(), sf.getTitle());
            }

            sb2.append("<h2>");
            sb2.append(sf.getTitle());
            if (sf.getImage().getUrl() != null) {
                sb2.append("<br><img src='");
                sb2.append(sf.getImage().getUrl());
                sb2.append("'><br>");
            }
            sb2.append(sf.getLink());
            sb2.append("<br>");
            sb2.append(sf.getDescription());
            sb2.append("<br>");
            sb2.append(sf.getCopyright());
            sb2.append("</h2>");

            sb1.append("<ul>");
            for (Object entry : sf.getEntries()) {
                SyndEntryImpl syndEntryImpl = (SyndEntryImpl) entry;
                sb1.append("<li><b><a href='");
                sb1.append(syndEntryImpl.getLink());
                sb1.append("' title='");
                sb1.append(syndEntryImpl.getTitleEx().getValue());
                sb1.append("' target=_blank>");
                sb1.append(syndEntryImpl.getTitle());
                sb1.append("</a></b></li>");
                syndEntryImpl = null;
            }
            sb1.append("</ul>");

        } catch (Exception ex) {
            ex.printStackTrace();
            sb1.append("FEED ERROR");
            sb2.append("FEED ERROR");

        } finally {
            session.setAttribute("coluna1", sb2);
            session.setAttribute("coluna2", sb1);
            session.setAttribute("tagCloud", tagCloudData());
            session.setAttribute("marquee", getBloList());
            response.sendRedirect("index.jsp");
            out.close();
        }
    }

    public static void updateFeed(FeedUrl f1) {
        f1.setOnline();
        PersistenceUtil.merge(f1);
    }

    private static final String getBloList() {
        try {
            return BloggerClient.getBlogListHtmlMarquee("malacma@gmail.com", "daonde12345").toString();
        } catch (Exception ex) {
            return "<marquee>Error" + ex + "</marquee>";
        }
    }

    public static final StringBuilder makeLayout(FeedUrl f1, StringBuilder sb2) throws MalformedURLException, IllegalArgumentException, FeedException, IOException {
        try {


            SyndFeed sf = FeedFactory.getInstance(f1.getUrl());

            if (sf.getImage() == null) {
                return null;
            }

            sb2.append(sf.getTitle());
            sb2.append("<br><img src='");
            sb2.append(sf.getImage().getUrl());
            sb2.append("'><br>");
            sb2.append(sf.getLink());
            sb2.append("<br>");
            sb2.append(sf.getDescription());
            sb2.append("<br>");
            sb2.append(sf.getCopyright());
            sb2.append("</h2>");

            sb2.append("<ul>");
            for (Object entry : sf.getEntries()) {
                SyndEntryImpl syndEntryImpl = (SyndEntryImpl) entry;
                sb2.append("<li><b><a href='");
                sb2.append(syndEntryImpl.getLink());
                sb2.append("' title='");
                sb2.append(syndEntryImpl.getTitleEx().getValue());
                sb2.append("' target=_blank>");
                sb2.append(syndEntryImpl.getTitle());
                sb2.append("</a></b></li>");
                syndEntryImpl = null;
            }
        } catch (IllegalArgumentException illegalArgumentException) {
            return null;
        } catch (FeedException feedException) {
            return null;
        } catch (IOException iOException) {
        }

        return sb2;
    }

    /**

    {
    items : [
    { label : 'jMaki', weight : 70},
    { label : 'Web2.0', weight : 150},
    { label : 'JSON', weight : 80},
    { label : 'JavaScript', weight : 145},
    { label : 'Java', weight : 100},
    { label : 'RSS', weight : 85},
    { label : 'Autocomplete', weight : 75},
    { label : 'Sun', weight : 65, href : 'http://www.sun.com'},
    { label : 'jMaki', weight : 150},
    { label : 'Web3.0', weight : 70},
    { label : 'Phobos', weight : 105},
    { label : 'Glassfish', weight : 120},
    { label : 'RSS2.0', weight : 75},
    { label : 'Web1.0', weight : 50},
    { label : 'JavaEE', weight : 75},
    { label : 'Jersey', weight : 115},
    { label : 'Roller', weight : 150},
    { label : 'CSS', weight : 105},
    { label : 'DHTML', weight : 65},
    { label : 'Netbeans', weight : 115, href : 'http://www.netbeans.com'}
    ]
    }"
     */
    private static StringBuilder tagCloudData() {
        StringBuilder sb = new StringBuilder();
        sb.append("{items : [");//Inicio

        Iterator<FeedUrl> it = FeedCatalog.getInstance().values().iterator();
        int nrTopChannels = 30;

        while (nrTopChannels-- > 0 && it.hasNext()) {
            FeedUrl f = it.next();
            String[] a1 = f.getTitulo().split(" ");
            int size = ((int) (f.getId().intValue() * Math.random()) + 30);
            size = (size > 150 ? 150 : size);
            sb.append("{ label : '" + a1[a1.length - 1] + "', weight : '" + size + "', href:'ServletRSS?rss=" + f.getUrl() + "'}");

            if (nrTopChannels > 0) {
                sb.append(",\n");
            }
        }

        sb.append("]}");//Fim
        return sb;

    }

    public static void search(HttpServletRequest request) throws MalformedURLException {
        String url = (request.getParameter("url") == null ? "http://edition.cnn.com/services/rss/" : request.getParameter("url"));

        // Make an instance of own our crawler
        FeedCrawler crawler = new FeedCrawler();

        // Create a "Link" object and set it as the crawler's root
        Link link = new Link(url);
        crawler.setRoot(link);
        crawler.setMaxDepth(3);

        //Inicia a thread de crawler
        Thread t = new Thread(crawler);
        t.start();
    }

    public static List<FeedUrl> findAllFeeds() {
        return PersistenceUtil.findAllFeedUrl();
    }

    public static List<FeedUrl> findAllOnffLine() {
        return PersistenceUtil.findOffLineFeeds();
    }
}
